package algotithm.jianzhioffer.test12;

/**
 * @author zhouyanxiang
 * @Date 2020-12-2020/12/14-15:06
 */
public class Solution {

    public static void main(String[] args) {
        char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
        String word = "ABCCED";
        Solution solution = new Solution();
        System.out.println(solution.exist(board, word));
    }

    public boolean exist(char[][] board, String word) {
        char[] array = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, array, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean dfs(char[][] board, char[] array, int i, int j, int k) {
        if (i < 0 || i >= board.length || j < 0 || j > board[0].length || board[i][j] != array[k]) {
            return false;
        }
        if (k == array.length - 1) {
            return true;
        }
        char tmp = board[i][j];
        board[i][j] = '1';
        boolean flag = dfs(board, array, i + 1, j, k + 1)
                || dfs(board, array, i - 1, j, k + 1)
                || dfs(board, array, i, j - 1, k + 1)
                || dfs(board, array, i, j + 1, k + 1);
        board[i][j] = tmp;
        return flag;
    }
}
